package com.example.common.utils;

import com.example.common.common.config.minio.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

@Component
public class MinioUtils {

    @Resource
    private MinioConfig prop;
    @Resource
    private MinioClient minioClient;


    //查找桶是否存在
    public Boolean bucketExists(String bucketName) {
        boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException("查询桶不存在"+e.getMessage(), e);
        }
        return found;
    }
    //列出桶的列表
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            throw new RuntimeException("查询错误"+e.getMessage(), e);
        }
    }

    //上传数据（字节流）
    public String uploadObject(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)){
            throw new RuntimeException("文件名识别错误");
        }
        String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        objectName = com.example.common.utils.StringUtils.replaceStr(objectName);
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket(prop.getBucketName())
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
           throw new RuntimeException("上传文件错误");
        }
        return objectName;
    }

    public String uploadBese64(String base64Image) {
        String base64Data = base64Image.split(",")[1];
        byte[] imageBytes = Base64.getDecoder().decode(base64Data);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
        String objectName = UUID.randomUUID().toString();
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket(prop.getBucketName())
                    .object(objectName)
                    .stream(inputStream, imageBytes.length, -1)
                    .contentType("image/png")
                    .build();
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            throw new RuntimeException("上传文件错误");
        }
        return objectName;
    }
//    public String uploadObject(byte[] fileContent, String fileName, String contentType){
//
//        try (InputStream inputStream = new ByteArrayInputStream(fileContent)) {
//            PutObjectArgs objectArgs = PutObjectArgs.builder()
//                    .bucket("hello")
//                    .object(fileName)
//                    .stream(inputStream, fileContent.length, -1)
//                    .contentType(contentType)
//                    .build();
//
//            // 文件名称相同会覆盖
//            minioClient.putObject(objectArgs);
//        } catch (Exception e) {
//            throw new RuntimeException("上传文件错误"+e.getMessage(), e);
//        }
//
//        return fileName;
//    }

    //下载数据（字节流）
    //先下载到本地
    public void downloadObject(String fileName){
        try {
            GetObjectResponse response = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(prop.getBucketName())
                    .object(fileName)
                    .build());
            response.transferTo(new FileOutputStream("F:\\FileDownTest"));
        } catch (Exception e) {
            throw new RuntimeException("下载失败"+e.getMessage(), e);
        }
    }

    //查询数据url
    public String getObjectUrl(String fileName){
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(prop.getBucketName())
                    .method(Method.GET)
                    //.expiry(3, TimeUnit.MINUTES)
                    .object(fileName)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException("查询url路径错误"+e.getMessage(), e);
        }
    }

    //删除数据
    public void removeObject(String fileName){
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(prop.getBucketName())
                    .object(fileName)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException("删除失败"+e.getMessage(), e);
        }
    }

    //查询数据列表
    public List<Item> getObjectList(){
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder()
                .bucket(prop.getBucketName())
                .build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            throw new RuntimeException("查询数据列表错误"+e.getMessage(), e);
        }
        return items;
    }
}
